0

I would like to change the styling attribute values of all elements that have the class "post-feature" and contain an attribute value of "http"

So the div element will look like the following:

<div class="post-feature" style="backgroundimage:url(http://local.test.com/test_image.jpg);">

So far the http check works. But I am not able to set the attribute value.

I have the following code

var features = document.getElementsByClassName(".post-feature")
[0].getAttribute("style");

if (features.includes("http")) {
features.setAttribute("background-color", "orange");

} else {

  alert('no change');

}
5
  • You need to be more specific. What attribute must contain a value of http? Commented Jun 6, 2017 at 1:53
  • @ Scott Marcus The background image attribute must contain http Commented Jun 6, 2017 at 1:57
  • Ok, but background image is not an "attribute", it's a CSS property. Commented Jun 6, 2017 at 1:58
  • drop the . from document.getElementsByClassName(".post-feature") for a start, because the lass name you are looking for doesn't start with a . Commented Jun 6, 2017 at 2:06
  • 1
    I updated my answer and added a second sample. Please review and comment, and it would also be great if you could accept the answer that helped you the most. Commented Jun 8, 2017 at 8:57

5 Answers 5

1

You can use querySelectorAll('.post-feature[style*="http"]') to find those elements.

Then simply iterate through them and i.e. set their background color with
element.style.backgroundColor = 'orange';

Now, if you want to make sure you only target elements having a background-image and http, you can use this selector:
querySelectorAll('.post-feature[style*="http"][style*="background-image"]')

Also, by adding an i (or I) just before the end bracket [style*="http"i], the value will be compared case-insensitively.

window.addEventListener('load', function() {
  var elements = document.querySelectorAll('.post-feature[style*="http"]');
  for (var i = 0; i < elements.length; i++) {
  
      elements[i].style.backgroundColor = 'orange';   /* add propert value */
      
      /*  replace class
      elements[i].className = 'myClass';
      */
      
      /*  add a class
      elements[i].classList.add('myClass');
      */
  }
  /* temp log */
  console.log('Found ', elements.length,' element(s)');
})
div {
  height: 40px;
  background-color: gray;
}
div + div {
  margin-top: 10px;
}
<div class="post-feature" style="background-image:url(http://local.test.com/test_image.jpg);"></div>

<div class="post-feature"></div>

<div class="post-feature" style="background-image:url(http://local.test.com/test_image.jpg);"></div>

<div class="post-feature"></div>


Updated

To only change styling, like colors etc., you don't even need a script, you can use CSS alone

div {
  height: 40px;
  background-color: gray;
}
div + div {
  margin-top: 10px;
}
/*  for elements that contain "http" and "background-image"  */
.post-feature[style*="http"i][style*="background-image"i] {
  background-color: orange;
}
<div class="post-feature" style="background-image:url(http://local.test.com/test_image.jpg);"></div>

<div class="post-feature"></div>

<div class="post-feature" style="background-image:url(HTTP://local.test.com/test_image.jpg);"></div>

<div class="post-feature"></div>

As a note, and as discussed in a few comments, if to make sure it is the background-image property that also contain the http in its url(), you can adjust the selector to this, which as well can be used without any script, as a CSS rule

.post-feature[style*="background-image:url(http"i] {
  background-color: orange;
}

The above selector can of course also be used in the first sample, like this

querySelectorAll('.post-feature[style*="background-image:url(http"i]')
Sign up to request clarification or add additional context in comments.

19 Comments

Suppose the elements look like this: <div class="post-feature" style="border-image: url("http:///images/border.png") 30 30 repeat;backgroundimage:url(test_image.jpg);"></div>. Your code will falsely pick up that div as one that should have an orange background.
@ScottMarcus One can create a scenario where almost anything is breakable. My answer shows how to use querySelectorAll, where it is possible to simpy add more selectors to avoid such falsey pick up
@ScottMarcus I also tested my solution with the markup in your answer, and it works perfect
First, your code does not work perfectly with my example code (above, in these comments). It incorrectly turns that div orange. Second, your solution has a very large vulnerability in it, hardly out of the ordinary code that one might expect.
First, to catch background and http, do querySelectorAll('.post-feature[style*="http"][style*="background-image"]') ...second, here is my code with your markup jsfiddle.net/ct8ko86f ... so I really don't understand what your are talking about
|
1

First, you can use querySelctorAll() with a CSS query that selects the elements with the class you desire and, in most cases, you should use this instead of getElementsByClassName() as that returns a "live node list" that causes the DOM to be re-scanned every time you access it.

Next, setAttribute() is for setting HTML element attributes. You are asking to change the value of a CSS property. While that could be accomplished with setAttribute('style', value), it is very "old-school" and not the best approach, nor is getAttribute('style') the best way to read a CSS property value (it won't work if the CSS was set from a style sheet).

Also, your code is trying to access: backgroundimage, but the property is accessed as background-image when working in CSS and backgroundImage when accessing it via JavaScript.

To access the inline styles applied to an HTML element, just access the style property of that element, followed by the name of the CSS property you are interested in. For example:

var bColor = element.style.backgroundColor;

If the style has been applied to the element from an internal style sheet or an external style sheet, the above approach won't work for you and you'll need to get it another way, via window.getComputedStyle():

var bColor = window.getComputedStyle(element, null).backgroundColor;

But, note that getComputedStyle() doesn't always return the same value that you set - - it's the value after the browser has computed all factors. In this case, even paths that you wrote as relative references (without the "http") will be returned as absolute paths (with the http).

So, here is a modern approach that correctly checks only the background-image CSS property for the presence of http.

NOTE: This solution tests for http specifically in the background-image property. Unlike most of the other answers given, this code will correctly ignore http in other CSS properties besides background-image. Examine the CSS of the last div to see this in action.

// querySelectorAll() is more efficient than getElementsByClassName()
var features = document.querySelectorAll(".post-feature");

// Loop over the list
for(var i = 0; i < features.length; i++){

  // Get access to the background-image property (called backgroundImage from JavaScript) value,
  // convert that value to lower case and check to see if "http" is in that value
  if(features[i].style.backgroundImage.toLowerCase().indexOf("http") > -1){
  
    // Set the CSS background-color property (called "backgroundColor" in JavaScript) to orange:
    features[i].style.backgroundColor = "orange";
    
    // Just for testing:
    features[i].textContent = features[i].style.backgroundImage;
    
  } else {
  
    alert("No change");
    
  }  
}
.post-feature { width:100%; height:50px; border:1px solid black; background-color:gray; color:yellow; }
<!-- The correct CSS property is "background-image", not "backgroundimage" -->
<div class="post-feature" style="background-image:url(http://local.test.com/test_image.jpg);"></div>
<div class="post-feature" style="background-image:url(test_image.jpg);"></div>
<div class="post-feature" style="background-image:url(http://local.test.com/test_image.jpg);"></div>
<div class="post-feature" 
     style="border-image: url('http:///images/border.png') 30 30 repeat;background-image:url(test_image.jpg);">I have "http" in one of my CSS properties, but not "background-image", so I shouldn't be orange.</div>

Comments

0

i think some wrong in your code, try this code

element.setAttribute("style", "background-color: orange;"); // bad

or

element.style.backgroundColor = "orange"; // good

2 Comments

Actually, the first bit of code is valid and will work (although the second bit is preferred).
two way is working perfect but I like the second because it's simple =)))
0

Use element.style.backgroundColor and indexOf

var features = document.getElementsByClassName(".post-feature")[0].getAttribute("style");

if (features.indexOf("http") > -1) {

  features.style.backgroundColor = "orange";

} else {

  alert('no change');

}

1 Comment

This code will return a false positive if any CSS property in the element contains http in its value, not just backgroundImage.
0

check this fiddle

https://jsfiddle.net/vywk72j8/2/

<div class="post-feature" style="background-image:url(http://local.test.com/test_image.jpg);">
tt</div>


var feature = document.getElementsByClassName("post-feature")[0];
if (feature.style.backgroundImage.indexOf("http") !== -1) {
    feature.style.backgroundColor = "orange";
} else {
    alert('no change');
}

In your code, you are fetching the attribute value in features

var features = document.getElementsByClassName(".post-feature")
[0].getAttribute("style");

Here features is a string containing attribute value, not an element so you cannot use it to set value.

3 Comments

This code will return a false positive if any CSS property in the element contains http in its value, not just backgroundImage.
my bad, I didnot go through the comments below the question. Thanks for pointing out
Also, what if the HTML as the style written as: url(HTTP://...)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.