jquery selector not working, why?

前端 未结 8 606
挽巷
挽巷 2021-01-18 09:29

I simply want to manipulate the elements within the #content div, but $(\'#content\') doesn\'t seem to work, and yet in other places it does! My relevant code i

相关标签:
8条回答
  • 2021-01-18 09:40

    Always remember!

    In jQuery when you want to access some attribute of the selected element, you use jQuery's .attr() API.

    Now you said this, document.getElementById("content").id Works, Equivalent jQuery statement of this line is

    $("#content").attr('id');

    For selecting attribute use .attr() For manipulating style/css use .css()

    YOu can also alter CSS properties of the selected element using .attr()

    Like .attr('style','your new style');

    0 讨论(0)
  • 2021-01-18 09:42

    id is a plain DOM property/attribute, and works with plain DOM objects, not jQuery objects.

    You would do this in jQuery:

    $("#content").attr('id');
    

    which equals:

    document.getElementById('content').id
    

    or

    $("#content")[0].id; //[0] gets the first DOM object in the collection
    
    0 讨论(0)
  • 2021-01-18 09:44

    $("#content") returns the jQuery collection containing the elmenent with id content. id is an attribute of an element, not a property of the collection. You would get the element's ID by chaining the attr() method off the collection:

    alert($("#content").attr('id'));
    

    Or, when eaching the collection, inside the function passed to each this will be the actual element, so you could access this.id

    $("#content").each(function () {alert(this.id);});
    
    0 讨论(0)
  • 2021-01-18 09:44

    you can get id by by using .attr("id") function. Use this code: $("#content").attr("id");

    0 讨论(0)
  • 2021-01-18 09:57

    There is a difference between a DOM element and a jQuery selection that contains a DOM element. A jQuery selection is a wrapper around the DOM object to make it easier to use. It doesn't have an id property, but a DOM element does. On the other hand, jQuery does provide a way to access elements' properties using the attr method:

    document.getElementById('content').id // access the id property of a DOM element
    $('#content').attr('id')              // use jQuery to select the element and access the property
    

    The length property, however, is provided by a jQuery selection, which is why that works fine for you.

    0 讨论(0)
  • 2021-01-18 10:02

    Try this

    $("#content").attr("id")
    
    0 讨论(0)
提交回复
热议问题