1

I'm trying to use jQuery to add some css to elements, but only if they have a certain attribute.

The reason why I'm not using just css is because the content for the site is too vast to go through and add classes to all the elements I want to style.

The jQuery code I'm using is this:

if ($('.body_text a').attr('name')) {
    $(this).css({
        'display': 'inline-block',
        'position': 'relative',
        'top': '-200px',
        'visibility': 'hidden'
    })
}

But this doesn't seem to be working. If I put an alert inside the if statement the alert works. Am I doing something wrong?

2
  • Try $('.body_text a[name]') Commented Jan 13, 2014 at 23:33
  • 1
    Per W3: The <a> name attribute is not supported in HTML5. Use the id attribute instead. Commented Jan 13, 2014 at 23:34

4 Answers 4

2

This is the jQuery selector you're looking for:

//de or: $('.body_text a[name="value"]').css({
$('.body_text a[name]').css({
    'display': 'inline-block',
    'position': 'relative',
    'top': '-200px',
    'visibility': 'hidden'
})

http://api.jquery.com/attribute-equals-selector/

You can do this with CSS too:

.body_text a[name] {
    display: inline-block;
    position: relative;
    top: -200px;
    visibility: hidden;
 }

http://www.w3schools.com/css/css_attribute_selectors.asp

Sign up to request clarification or add additional context in comments.

Comments

0

It's because $(this) doesn't actually refer to anything — It needs to be placed in a function to refer to something.

However, the following code goes through all as with a name attribute, and applies the styles to each one.

$('.body_text a[name]').css({
     'display': 'inline-block',
     'position': 'relative',
     'top': '-200px',
     'visibility': 'hidden'
})

Comments

0

Viewing the documentation:

The .attr() method gets the attribute value for only the first element in the matched set. To get the value for each element individually, use a looping construct such as jQuery's .each() or .map() method.

I guess this is your problem?

1 Comment

Is this an answer? This seems like a comment.
0

Try this it should do the trick:

if( $('.body_text a').attr('name') == "TEXT HERE" ){
     // Do something
} else {
     // Do Something else
}

Make sure to loop through using the .each on the element you are looking for.

$('.body_text a').each(function(){

1 Comment

You can do this plainly with css though. .body_text a[name="Text Here] { followed by your css }

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.