user15036136
user15036136

Reputation:

edit style properties of label without ID

I am working on a website whose HTML and CSS I don't have access to.

I need to hide the label in the code below.

<div id ="area" class="dhx_cal_lsection">
  "Text"
  <label class="dhx_fullday">
    <input type="checkbox" name="full_day" value="true">
    "Text"
  </label>
</div>

document.getElementById() won't work because it doesn't have an ID.

I tried document.getElementsByClassName("dhx_fullday")[0].style.visibility = "hidden"; but it said "cannot access visibility of undefined" in the console.

Edit: Turns out the reason it couldn't access visibility of "dhx_fullday" was because it wasn't loaded at the time of execution.

Upvotes: 1

Views: 909

Answers (2)

Tanner Dolby
Tanner Dolby

Reputation: 4421

When you want to select a single element from the DOM with JavaScript, using getElementById() or querySelector() will do the trick. There is no need to return a live HTMLCollection or static (not live) NodeList to select a single element. Since you can't use getElementById because the <label> doesn't have an id, just utilize querySelector() to select the label element and hide it. Or hide the content in a more accessible manner for those using assistive technologies with the clip-pattern.

You could hide the <label> in a few different ways:

  1. Add inline style directly like element.style.display = "none"
  2. Create a CSS class to add, ie .hide { display: none } and then element.classList.add("hide")

const label = document.querySelector(".dhx_fullday");
label.style.display = "none"; /* basic example */
<div id ="area" class="dhx_cal_lsection">
  "Text"
  <label class="dhx_fullday">
    <input type="checkbox" name="full_day" value="true">
    "Text in label"
  </label>
</div>

Upvotes: 1

Elham Dabiri
Elham Dabiri

Reputation: 415

You can use this:

document.getElementsByClassName("dhx_fullday")[0].style.display = "none"

Upvotes: 0

Related Questions