How do I add text to specific div element using jQuery?

后端 未结 5 1160
南笙
南笙 2021-02-14 05:08

I am having a problem with jquery. My HTML is

相关标签:
5条回答
  • 2021-02-14 05:43

    Several possible alternatives

    Others have provided their answers already but let me give you some more alternatives.

    $("span.test:first").text("Welcome");
    $("#first span.test").text("Welcome");
    $("span.test").first().text("Welcome");
    $("span.test").eq(0).text("Welcome");
    $("span.test", "#first").text("Welcome");
    

    The second and last one likely being the fastest because they target particular container by ID.
    (internal jQuery optimisations may prove me wrong with any future version)

    Performance comparison

    Here's a JSPerf test that performance compares upper possibilities. As anticipated, the second and last approaches are the fastest of all because element selection is much simplified. I've tried running them on Chrome and you may run them in other browsers if you want to and see differences.

    0 讨论(0)
  • 2021-02-14 05:47

    You need to use the :first selector to say that you only want to add text to the first element the selector finds. Try this:

    $j('span.test:first').text('Welcome');
    

    Example fiddle

    Alternatively, you can use the id of the parent div to make the selector unique:

    $j('#first .test').text('Welcome');
    
    0 讨论(0)
  • 2021-02-14 05:54

    Since you have an id, which usually is unique on one page, it woud be best to use the following:

    $("#first span.test").text("Welcome");
    
    0 讨论(0)
  • 2021-02-14 05:57
    $('#first span.test').text('Welcome');
    

    jQuery selectors are CSS selectors extended with a bit of magic. You can find everything you need to know here: http://api.jquery.com/category/selectors/

    0 讨论(0)
  • 2021-02-14 05:58

    In this example you can do what RoRyMcCrossan For general selection i recommend you to look at this :http://api.jquery.com/child-selector/

    Or you can use this

    http://api.jquery.com/eq-selector/

    0 讨论(0)
提交回复
热议问题