简体   繁体   中英

How do I get the particular value from same multiple div class name in javascript?

here's the HTML:

 <div class="hMZdhd">Additional access <div class="OcFGjf"> <div role="listitem" class="wnt0Xd">View your approximate age</div> <div role="listitem" class="wnt0Xd">View your language preferences</div> </div> </div> <div class="hMZdhd">March 20, 12:06 PM</div>

I want to access the one value of div class "hMZdhd", but my javascript code returns all the values of class with name "hMZdhd".

Here's My sample javascript code:

document.getElementsByClassName("hMZdhd")[0].innerHTML

Output Should be: March 20, 12:06 PM

Any Help would be appreciated
Thanks

The element you want to display is at the last index ( .length - 1 ) of the array returned by your class selection,

[0] returns the first element matching the class hMZdhd (ie <div class="hMZdhd">Additional access[…]</div> ).

 var elms = document.getElementsByClassName("hMZdhd"); console.log(elms[elms.length - 1].innerHTML)
 <div class="hMZdhd">Additional access <div class="OcFGjf"> <div role="listitem" class="wnt0Xd">View your approximate age</div> <div role="listitem" class="wnt0Xd">View your language preferences</div> </div> </div> <div class="hMZdhd">March 20, 12:06 PM</div>

You can try console.log(document.getElementsByClassName("hMZdhd")) to display the full array returned by getElementsByClassName("hMZdhd") in this kind of situation. It's often helpfull.

Since you need the content of last div with that class you can calculate the index of last div item and get the content like:

 var element = document.getElementsByClassName("hMZdhd"); var val = element[element.length-1].innerHTML; console.log(val);
 <div class="hMZdhd">Additional access <div class="OcFGjf"> <div role="listitem" class="wnt0Xd">View your approximate age</div> <div role="listitem" class="wnt0Xd">View your language preferences</div> </div> </div> <div class="hMZdhd">March 20, 12:06 PM</div>

You need to use innerText instead of innerHTML on last index .

Your code:

document.getElementsByClassName("hMZdhd")[0].innerHTML

Code you want:

var items = document.getElementsByClassName("hMZdhd");
var outputYouWant = items[items.length-1].innerText;

EDIT: Code edited to get last item. BTW innerText is the truest answer for the asked output, not innerHTML.

Is this what you want?

 var div = document.getElementsByClassName("hMZdhd")[0]; div.style.display = "none";
 <div class="hMZdhd">Additional access <div class="OcFGjf"> <div role="listitem" class="wnt0Xd">View your approximate age</div> <div role="listitem" class="wnt0Xd">View your language preferences</div> </div> </div> <div class="hMZdhd">March 20, 12:06 PM</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM