4

How do you alter the content of a <div> using javascript when the <div> has no id or class.

I know that using something like document.getElementById('foo').innerHTML = 'Your content'; Could have been used if the <div> had an id. But in my case the content I want to alter is like this

<div unselectable="on" style="position: absolute; padding: 2px; top: 0px; left: 1px; background-color: rgb(255, 102, 0); color: white;">BOO</div>

I am partial to using document.getElementsByTagName("div")[0].innerHTML = "BOO"; to find it but how do I then proceed to modify its content? Also is this a good way to doing things?

4
  • Is that the only div in your document? May 14, 2015 at 5:33
  • No there are other div too but that is the only one with that content Boo
    – Rick Roy
    May 14, 2015 at 5:33
  • You need to have valid identifier to your element to manipulate it using JS.. by using getElementsByTagName, you need to know the index of element..
    – Rayon
    May 14, 2015 at 5:34
  • @panther it is inside this one <div unselectable="on" class="calendar_white_corner_inner"></div>
    – Rick Roy
    May 14, 2015 at 5:36

1 Answer 1

7

No there are other div too but that is the only one with that content Boo

If that case, you can find by :contains

$("div:contains('BOO')").html('hello');
6
  • OP didnt say he is using jQuery. May 14, 2015 at 5:37
  • 2
    @Warlock, they did. They tagged it jQuery :) May 14, 2015 at 5:38
  • @TheWarlock He did. See tagged. May 14, 2015 at 5:39
  • I have jquery 1.9 loaded in the page @The Warlock
    – Rick Roy
    May 14, 2015 at 5:39
  • 2
    @TheWarlock : Or maybe he saying that, either native javascript or jquery answers are acceptable then. May 14, 2015 at 5:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.