Как получить тег span внутри div в jQuery и назначить текст? - PullRequest
25 голосов
/ 20 апреля 2010

Я использую следующее,

<div id='message' style="display: none;">
  <span></span>
 <a href="#" class="close-notify">X</a>
</div>

Теперь я хочу найти диапазон внутри div и присвоить ему текст ...

function Errormessage(txt) {
    $("#message").fadeIn("slow");
    // find the span inside the div and assign a text
    $("#message a.close-notify").click(function() {
        $("#message").fadeOut("slow");
    });
}

Ответы [ 5 ]

52 голосов
/ 20 апреля 2010

Попробуйте это:

$("#message span").text("hello world!");

Смотри это в своем коде!

function Errormessage(txt) {
    var m = $("#message");

    // set text before displaying message
    m.children("span").text(txt);

    // bind close listener
    m.children("a.close-notify").click(function(){
      m.fadeOut("slow");
    });

    // display message
    m.fadeIn("slow");
}
18 голосов
/ 20 апреля 2010
$("#message > span").text("your text");

или

$("#message").find("span").text("your text");

или

$("span","#message").text("your text");

или

$("#message > a.close-notify").siblings('span').text("your text");
4 голосов
/ 20 апреля 2010

Попробуйте это

$("#message span").text("hello world!");

function Errormessage(txt) {
    var elem = $("#message");
    elem.fadeIn("slow");
    // find the span inside the div and assign a text
    elem.children("span").text("your text");

    elem.children("a.close-notify").click(function() {
        elem.fadeOut("slow");
    });
}
0 голосов
/ 17 апреля 2019

Ваниль JS, без JQuery:

document.querySelector('#message span').innerHTML = 'hello world!'

Доступно во всех браузерах: https://caniuse.com/#search=querySelector

0 голосов
/ 09 ноября 2011
function Errormessage(txt) {
    $("#message").fadeIn("slow");
    $("#message span:first").text(txt);
    // find the span inside the div and assign a text
    $("#message a.close-notify").click(function() {
        $("#message").fadeOut("slow");
    });
}
...