Get element inside element by class and ID - JavaScript

JavascriptGetelementbyidGetelementsbyclassname

Javascript Problem Overview


Alright, I've dabbled in JavaScript before, but the most useful thing I've written is a CSS style-switcher. So I'm somewhat new to this. Let's say I have HTML code like this:

<div id="foo">
    <div class="bar">
        Hello world!
    </div>
</div>

How would I change Hello world! to Goodbye world!?

I know how document.getElementsByClassName and document.getElementById work, but I would like to get more specific. Sorry if this has been asked before.

Javascript Solutions


Solution 1 - Javascript

Well, first you need to select the elements with a function like getElementById.

var targetDiv = document.getElementById("foo").getElementsByClassName("bar")[0];

getElementById only returns one node, but getElementsByClassName returns a node list. Since there is only one element with that class name (as far as I can tell), you can just get the first one (that's what the [0] is for—it's just like an array).

Then, you can change the html with .textContent.

targetDiv.textContent = "Goodbye world!";

var targetDiv = document.getElementById("foo").getElementsByClassName("bar")[0];
targetDiv.textContent = "Goodbye world!";

<div id="foo">
    <div class="bar">
        Hello world!
    </div>
</div>

Solution 2 - Javascript

You can do it like this:

var list = document.getElementById("foo").getElementsByClassName("bar");
if (list && list.length > 0) {
    list[0].innerHTML = "Goodbye world!";
}

or, if you want to do it with with less error checking and more brevity, it can be done in one line like this:

document.getElementById("foo").getElementsByClassName("bar")[0].innerHTML = "Goodbye world!";

In explanation:

  1. You get the element with id="foo".
  2. You then find the objects that are contained within that object that have class="bar".
  3. That returns an array-like nodeList, so you reference the first item in that nodeList
  4. You can then set the innerHTML of that item to change its contents.

Caveats: some older browsers don't support getElementsByClassName (e.g. older versions of IE). That function can be shimmed into place if missing.


This is where I recommend using a library that has built-in CSS3 selector support rather than worrying about browser compatibility yourself (let someone else do all the work). If you want just a library to do that, then Sizzle will work great. In Sizzle, this would be be done like this:

Sizzle("#foo .bar")[0].innerHTML = "Goodbye world!";

jQuery has the Sizzle library built-in and in jQuery, this would be:

$("#foo .bar").html("Goodbye world!");

Solution 3 - Javascript

If this needs to work in IE 7 or lower you need to remember that getElementsByClassName does not exist in all browsers. Because of this you can create your own getElementsByClassName or you can try this.

var fooDiv = document.getElementById("foo");

for (var i = 0, childNode; i <= fooDiv.childNodes.length; i ++) {
    childNode = fooDiv.childNodes[i];
    if (/bar/.test(childNode.className)) {
        childNode.innerHTML = "Goodbye world!";
    }
}

Solution 4 - Javascript

The easiest way to do so is:

function findChild(idOfElement, idOfChild){
  let element = document.getElementById(idOfElement);
  return element.querySelector('[id=' + idOfChild + ']');
}

or better readable:

findChild = (idOfElement, idOfChild) => {
    let element = document.getElementById(idOfElement);
    return element.querySelector(`[id=${idOfChild}]`);
}

Solution 5 - Javascript

Recursive function :

function getElementInsideElement(baseElement, wantedElementID) {
    var elementToReturn;
    for (var i = 0; i < baseElement.childNodes.length; i++) {
        elementToReturn = baseElement.childNodes[i];
        if (elementToReturn.id == wantedElementID) {
            return elementToReturn;
        } else {
            return getElementInsideElement(elementToReturn, wantedElementID);
        }
    }
}

Solution 6 - Javascript

you can use getElementById or getElementsByClassName on DOM Elements too. and not just the document

var targetDiv = document.getElementById("foo").getElementsByClassName("bar")[0];
targetDiv.textContent = "Goodbye world!";

<div id="foo">
    <div class="bar">
        Hello world!
    </div>
</div>

Solution 7 - Javascript

We can also make use of CSS selectors with querySelector

var targetDiv = document.querySelector('#foo .bar');
targetDiv.textContent = "Goodbye world!";

Solution 8 - Javascript

You should not used document.getElementByID because its work only for client side controls which ids are fixed . You should use jquery instead like below example.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>                                                                                                             
<div id="foo">
   <div class="bar"> 
          Hello world!
     </div>
</div>

use this :

$("[id^='foo']").find("[class^='bar']")

// do not forget to add script tags as above

if you want any remove edit any operation then just add "." behind and do the operations

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTanner BabcockView Question on Stackoverflow
Solution 1 - JavascriptJoseph MarikleView Answer on Stackoverflow
Solution 2 - Javascriptjfriend00View Answer on Stackoverflow
Solution 3 - JavascriptJohn HartsockView Answer on Stackoverflow
Solution 4 - JavascriptBenjamin WernerView Answer on Stackoverflow
Solution 5 - JavascriptAvi ShimshilashviliView Answer on Stackoverflow
Solution 6 - JavascriptJhonny SANView Answer on Stackoverflow
Solution 7 - Javascriptrajesh kumarView Answer on Stackoverflow
Solution 8 - Javascripthardik akbariView Answer on Stackoverflow