Scott
Scott

Reputation: 35

Modifying a form label text with JS using only the "for" attribute as a selector

I have access to a form that I need to modify a labels text. I can only add JS to the page otherwise I'd just change the HTML or even replace the text with CSS.

To make matters worse the label doesn't have an ID or NAME other than it's "for" attribute.

<label for='camper1Grade' class="control-label required">Grade entering, Fall 2020</label>

If I could just edit the CSS I would do this:

   <style>
    label[for=camper1Grade]:before {content: "Grade completing, Spring 2020";}
    label[for=camper1Grade] { font-size: 0px;}
    label[for=camper1Grade]:after { content: "*";color: red;}
    </style>

But like I mentioned I can't add CSS directly.

I'm a pretty good CSS coder but know very little about JS. I'm sure there is a solution I just can't find a good explanation of how to do this. Thanks in advance to anyone who has an idea.

Upvotes: 1

Views: 113

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370799

Almost all elements you can select with CSS you can also select with Javascript and querySelector. Unfortunately, ::before and ::after psuedo-elements are not among them. But, you can always inject another stylesheet using Javascript:

document.body.appendChild(document.createElement('style')).textContent = `
    label[for=camper1Grade]::before { content: "Grade completing, Spring 2020"; }
    label[for=camper1Grade] { font-size: 0px; }
    label[for=camper1Grade]::after { content: "*"; color: red;}
`;

(note the two colons, which is the standard for CSS3)

Upvotes: 4

Related Questions