Change inline css of an element without an id or class - javascript

It's pretty simple to change the style of an element when it has a class. I thought it would be simple to change the style of an element that has no class or id too, but I haven't been able to figure it out.
The html page looks something like this:
<!DOCTYPE html>
<html>
<head>
<title>ExamplePage</title>
</head>
<body>
<h1>Lorem ipsum</h1>
<p style="display: none">The style shouldn't change</p>
<section class="container_class">
<p style="display: none">The display part of the inline css should be deleted or modified to inline</p>
<p style="display: none">The display part of the inline css should be deleted or modified to inline</p>
<p style="display: none">The display part of the inline css should be deleted or modified to inline</p>
</section>
<p style="display: none">The style shouldn't change</p>
</body>
</html>
Since I'm trying to build a google chrome extension I've been using contentscripts.
I haven't figured out how to select the specific element although I have seen something similar to this idea.
I've searched the internet on how to select a specific element based on the inline css. I couldn't find anything helpful.
This is my content.js:
var ps = document.querySelectorAll("section.container_class > p");
var i;
for (i = 0; i < ps.length; i++) {
ps.style.display = "inline";
}
I'm new to coding in javascript, so the code might not make sense at all. It's just an idea on how to change the inline css. I'm trying to learn by doing a mini-project like this.

You're nearly there.
The bug is in the for loop. It should be:
var ps = document.querySelectorAll("section.container_class > p");
var i;
for (i = 0; i < ps.length; i++) {
ps[i].style.display = "inline";
}
Note the square bracket array access notation on the ps variable.
ie. for every iteration of the loop, access the ith index of the array ps.

"document.querySelectorAll" returns an Array containing all the elements that you have specified (in this case: "section.container_class > p"). So when you want to iterate through the entire Array you will have to use an index.
Basically all you forgot was to add [i] in your block of code.
var ps = document.querySelectorAll("section.container_class > p");
var i;
for (i = 0; i < ps.length; i++) {
ps[i].style.display = "inline";
}
However you should try to use the let and const keywords instead of var.
Also i is defined as a global variable and you don't want that because it might interfer with locally defined variables. So instead you should declare it in the for-loop "head".
A newer version might look something like this:
const PS = document.querySelectorAll("section.container_class > p");
for (let i = 0; i < ps.length; i++) ps[i].style.display = "inline";

var ps is defined to array as it selected for querySelectorAll. Seems there is no number for ps array in for loop.
var ps = document.querySelectorAll("section.container_class > p");
var i;
for (i = 0; i < ps.length; i++) {
//Here should be array num.
ps[i].style.display = "inline";
}

Related

How to target a data-ref with a specific value and add a style using javascript

I want to target a data-ref with a specific value and add an inline style="display:none;" to it.
How can this be achived? Can someone help me please?
This is how it looks:
<div data="{test-bubble}}" data-ref="bubbles[test-link.com/test]" class="bubbles" state="default">
</div>
I tried this but it does not work:
var bubbleremoval = document.querySelector('[data-ref="bubbles[test-link.com/test]"]')
bubbleremoval.style.display = "none";
"""Your code should work if you are applying to a single element since query selector returns one element but for several elements you could fetch by classname and loop through the elements and remove display for each"""
var bubbleremoval = document.getElementsByClassName('bubbles')
for (let i = 0; i < bubbleremoval.length; i++) {
bubbleremoval[i].style.display = "none";
}

Create elements using function parameters, Javascript

First time question asker, go easy on me. I think I've thoroughly looked through Stack so as to not ask a repeated question.
I have a function.
function createDivs(num) {
for(let inc = 0; inc < num; inc++) {
let div = document.createElement('div'),
tab_content = document.getElementsByClassName('tab-content');
div.className = 'classname';
div.id = `number-${inc}`;
div.innerHTML = 'did it work?';
tab_content.innerHTML = div;
}
}
Where the HTML is just simply
<div class="tab-content">
<script>
createDivs(4);
</script>
</div>
I've tried other methods like
let tab_content = document.getElementsByClassName('tab-content');
tab_content.innerHTML = '<div class="classname" id=`number-${inc}`>did it work?</div>';
as well as ton other variations with the '' "" and `` and that didn't work neither.
I have also tried tab_content.appendChild(div); and that didn't work either.
In reality this is a downgrade of what my actual code is because I'm creating tons of elements that need things in them, but I can't even get this bit to work. It doesn't even work if I remove the for loop. Also I did see this post, hence why I tried the appendChild, but again that also didn't work.
It looks to me like you want not to set the innerHTML, but actually to append several child nodes. In addition to that, there were a couple of errors in your code (getElementsByClassName) returns an array-like object, not just one object, so you'll need to select one to add your divs to.
Also, you named your i variable in the loop inc not i, so it doesn't actually increment the loop. Take a look at the below rewritten code and see if that does what you're looking for.
function createDivs(num) {
for(let inc = 0; inc < num; inc++) {
let div = document.createElement('div'),
tab_content = document.getElementsByClassName('tab-content');
div.className = 'classname';
div.id = `number-${inc}`;
div.innerHTML = 'did it work?';
tab_content[0].appendChild(div);
}
}
(function(){createDivs(4)})()
<div class="tab-content">
</div>
You had a few typos in your code. usin i++ instead of inc++ in your loop. Not accessing tab_content as an array and using innerHtml instead of appendChild. Fixed code is below.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function createDivs(num) {
for(let inc = 0; inc < num; inc++) {
let div = document.createElement('div'),
tab_content = document.getElementsByClassName('tab-content')[0];
div.className = 'classname';
div.id = `number-${inc}`;
div.innerHTML = 'did it work?';
tab_content.appendChild(div);
}
}
</script>
</head>
<body>
<div class="tab-content">
<script>
createDivs(4);
</script>
</div>
</body>
</html>
your for loop does not increment its control variable. Change it to
for(let inc = 0; inc < num; inc++) {
and getElementsByClassName returns an array like object, not a single element. So you need to change it to
tab_content = document.getElementsByClassName('tab-content')[0];

On a target page with multiple id's, script is acting only on the first one

I'm filling in a text box using Greasemonkey. It's working, but the page has more than one <input> with the same id, and GM is only filling in the first one.
The page's HTML (repeated 3 times):
<input type="text" id="se" value="" class="form">
My GM Code:
document.getElementById("se").value = "na";
How can I set the 2nd or 3rd <input> too?
Yeah, pages with malformed HTML are a right pain. Fortunately, querySelectorAll() usually works as one would hope on such pages. (Alas, libraries, even jQuery, usually don't handle the malformed pages as well.)
In this case, the following code should work for you:
var badInputs = document.querySelectorAll ("#se");
for (var J = badInputs.length - 1; J >= 0; --J) {
var tInput = badInputs[J];
tInput.value = "na";
}
You can see the code in action at jsFiddle.
You could iterate the input elements on the page, looking for a specific id value:
var elements = document.getElementsByTagName('input');
for(var i = 0; i < elements.length; i++)
{
if(elements[i].id === "se")
{
elements[i].value = "na";
}
}
fiddle

How to remove all HTML tag by using the loop with Javascript

<div id='images'><img id='center_loadingImage' align='middle' src='loading.gif' alt='Loading Image'></div>
How to remove all <div> with the loop with Javascript?
Here is my code:
var value = document.getElementsByTagName("images");
for (var i = 0; i < value.length; i++) {
$(value[i]).remove();
}
You can only use same id value once per page. Change it to class, i.e. images
You will then have multiple div with class images and will be able to easily remove the spinners like this:
$(".images").remove();
If you have a lot of spinners, just wrap them with a div and remove the div. Something like this:
HTML:
<div id="jedi-wrapper">
<div class="images">
...
</div>
</div>
jQuery:
$("#jedi-wrapper").remove();
From the image, it looks like you are loading some values using AJAX. Why don't you remove the image on success?
Hope that helps
Seem like you want to remove all div with id images, but id is unique, you can use class instead:
<div class='images'><img class='center_loadingImage' align='middle' src='loading.gif' alt='Loading Image'></div>
then you can do:
$('.images').remove()
With your code you can do this:
document.getElementsByClassName("images").remove();
or more like jQuery:
$('.images').remove();
Althoug you can try this too:
var value = document.getElementsByClassName("images");
for (var i = 0; i < value.length; i++) {
$(value).eq(i).remove();
} //-------^^^^^^--------------you can make use of `.eq()` here
What your issue is there is no tag name like 'images' as your var suggests.
var value = document.getElementsByTagName("images");
images is the class name so you can use this:
document.getElementsByClassName("images")
Get element by ID, there's nothing with document.getElementsByTagName("images")
var c = document.getElementById('images');
var i, item = c.childNodes;
for (i = item.length; i--;) {
c.removeChild(item[i]);
}
You should probably be using class="images" instead of id="images" if that element is being rendered multiple times.
But to do this in a loop with raw javascript, you will need to first get the elements, convert them to an array, and then remove them in a loop.
var imageElements = doc.getElementsByClassName('images'),
images = Array.prototype.slice.call(imageElements);
for (var i = 0, l = images.length; i < l; i++) {
images[i].remove();
}
Notice that I don't just loop through imageElements... That's because getElementsBy...() returns a live list, so as soon as you remove() one of them, the list will be mutated and you will start running into undefined elements and javascript errors. To solve this, simply convert the live list to an array with Array.prototype.slice.call() and then loop through that array, removing the elements from the page.

Changing css style sheet with javascript

I have the following:
<style>
.el {color: blue;}
</style>
<div class="el">bla bla</div>
<div class="el">bla bla 123</div>
And i need to use JavaScript to change the color in .el.
I know about document.styleSheets but that seems kind of crude, having to loop search for the class i want to change it that way. Isn't there some better (lighter) way to do this nowadays? Something like
document.stylesheets.getclass('.el').color = 'red';
Thanks.
You're on the right track. The method you're looking for is getElementsByClassName, not getClass. It returns an array, and then you simply loop through the array and assign the new color.
var el = document.getElementsByClassName('el'),
i;
for (i = 0; i < el.length; i += 1) {
el[i].style.color = 'red';
}
Demo
P.S., obviously, this changes the style, not the stylesheet.
Try this:
var elem = document.getElementsByClassName('el');
for (var i = 0; i < elem.length; i++) {
elem[i].style.color = '#aaaaaa';
}

Categories

Resources