How to Get Element by Class in JavaScript

How to get element by class name?

The name of the DOM function is actually getElementsByClassName, not getElementByClassName, simply because more than one element on the page can have the same class, hence: Elements.

The return value of this will be a NodeList instance, or a superset of the NodeList (FF, for instance returns an instance of HTMLCollection). At any rate: the return value is an array-like object:

var y = document.getElementsByClassName('foo');
var aNode = y[0];

If, for some reason you need the return object as an array, you can do that easily, because of its magic length property:

var arrFromList = Array.prototype.slice.call(y);
//or as per AntonB's comment:
var arrFromList = [].slice.call(y);

As yckart suggested querySelector('.foo') and querySelectorAll('.foo') would be preferable, though, as they are, indeed, better supported (93.99% vs 87.24%), according to caniuse.com:

  • querySelector(all)
  • getElementsByClassName
  • Don't use w3schools to learn something
  • Refer to MDN for accurate information

Get element inside element by class and ID - 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>

Javascript: How to get only one element by class name?

document.getElementsByClassName('className') would always return multiple elements because conceptually Classes are meant to be applied to multiple elements. If you want only the first element in the DOM with that class, you can select the first element out of the array-like HTMLCollection returned.

var elements = document.getElementsByClassName('className');
var requiredElement = elements[0];

Else, if you really want to select only one element. Then you need to use 'id' as conceptually it is used as an identifier for unique elements in a Web Page.

// HTML
<div id="myElement"></div>

// JS
var requiredElement = document.getElementById('myElement');

Get elements by class name in a certain div through Javascript

You can use the element[property*="val"] to select all elements with property beginning with "val" - in this case, any class that starts with "f", and then select their .input-text children.

Also, you're trying to get elements with id f0, when these divs are marked with class f0.

const inputs = document.querySelectorAll('[class*="f"] .input-text');

for (const element of inputs)

console.log(element.textContent.trim());
<div class="f0">

<div class="input-text">

inside f0

</div>

</div>

<div class="f1">

<div class="input-text">

inside f1

</div>

</div>

Get element inside element by class - JavaScript

The getElementsByClassName() method returns a collection of all elements in the document with the specified class name, as a NodeList object.

var firstChild = document.getElementsByClassName('demo')[0].children[0];

console.log(firstChild)
<div class ="demo">

<p>some text</p>

<p>some other text</p>

</div>

get second element by class name if it exists

Try this:

const elements = document.querySelectorAll('.test');

if (elements[1]) {

elements[1].innerText = 'Hithere';

}
<div class="test">hi</div>

<div class="test">hi</div>

<div class="test">hi</div>

How to add a class to a given element?

If you're only targeting modern browsers:

Use element.classList.add to add a class:

element.classList.add("my-class");

And element.classList.remove to remove a class:

element.classList.remove("my-class");

If you need to support Internet Explorer 9 or lower:

Add a space plus the name of your new class to the className property of the element. First, put an id on the element so you can easily get a reference.

<div id="div1" class="someclass">
<img ... id="image1" name="image1" />
</div>

Then

var d = document.getElementById("div1");
d.className += " otherclass";

Note the space before otherclass. It's important to include the space otherwise it compromises existing classes that come before it in the class list.

See also element.className on MDN.

Javascript Click on Element by Class

I'd suggest:

document.querySelector('.rateRecipe.btns-one-small').click();

The above code assumes that the given element has both of those classes; otherwise, if the space is meant to imply an ancestor-descendant relationship:

document.querySelector('.rateRecipe .btns-one-small').click();

The method getElementsByClassName() takes a single class-name (rather than document.querySelector()/document.querySelectorAll(), which take a CSS selector), and you passed two (presumably class-names) to the method.

References:

  • document.getElementsByClassName().
  • document.querySelector().


Related Topics



Leave a reply



Submit