How to access html element label without an ID or class?

I am trying to change the value by innerHtml property of label.

<span class="input-container">

    <input type="checkbox"  name="opt-in" id="opt-in" class="checkbox opt-in" value="1235454905" />

    <label for="opt-in"> We may collect, use and process data according to our Privacy Policy</label>

</span>

I can't add id or class to the level because it's a WordPress short code form. Is there any way? Thanks.

Upvotes: 1

Views: 1776

Answers (5)

TPHughes
TPHughes

Reputation: 1627

You can select an element sing any of the attributes, and wrapping it in square braces. JQuery is required for this.

In your case you could use ("[for=opt-in") or ("label[for=opt-in")

If the element has a name you could also use ("[name=element_name")

Take a look here for some of the available methods, as well as the square brackets. https://www.w3schools.com/jquery/jquery_ref_selectors.asp

Upvotes: 0

Aryan amish
Aryan amish

Reputation: 1

you can add the class or id by going in WordPress admin page => appearance => editor. there you can add class or id using the WordPress editor.

Upvotes: 0

Niklesh Raut
Niklesh Raut

Reputation: 34914

You can simply use the label tag, or by attribute for='opt-in' or label of parent to get label's innerHTML

console.log(document.querySelector("label").innerHTML);
console.log(document.querySelector("label[for='opt-in']").innerHTML);
console.log(document.querySelector("#opt-in").parentElement.querySelector("label").innerHTML);
<span class="input-container">

    <input type="checkbox"  name="opt-in" id="opt-in" class="checkbox opt-in" value="1235454905" />

    <label for="opt-in"> We may collect, use and process data according to our Privacy Policy</label>

</span>

Upvotes: 5

A.Martinez
A.Martinez

Reputation: 133

Well, you can get the span by using document.getElementsByClassName() Notic that this method will return an Array, so you will have to access the first component, if there's only one element with that ClassName. After that, you can get the label by document.getElementsByClassName()[0].childNodes[1].

Upvotes: 0

Michael Karpinski
Michael Karpinski

Reputation: 353

document.getElementsByTagName("label")[0] will select the first label element on the page. This approach only works if you know exactly where the element is in your HTML.

Upvotes: 0

Related Questions