B Robster
B Robster

Reputation: 42003

Within a div containing both text and an HTML element, how to change only the text and not the element, using JQuery?

I am using a plugin that renders a div style "button", whose html looks like this:

<div id="div-id">
  "Button Label"
  <input type="file" . . . >
</div>

How do I dynamically change the "Button Label" text with jQuery, while leaving the input intact?

I've tried using .text() but that replaces the input as well.

(Note: I have no control over the HTML that the plugin renders so I'm stuck with this structure).

Thanks!

Upvotes: 0

Views: 164

Answers (4)

jfriend00
jfriend00

Reputation: 707198

You can directly access the text node in plain javascript with code like this:

function getFirstTextNode(el) {
    var children = el.childNodes;
    for (var i = 0; i < children.length; i++) {
        if (children[i].nodeType == 3) {
            return(children[i]);
        }
    }
}

var textNode = getFirstTextNode(document.getElementById("div-id"));
textNode.nodeValue = "New Label ";

Upvotes: 1

Anurag
Anurag

Reputation: 141869

You could iterate through each node, and look for text nodes with matching content. Once found, only work on that node.

function isTextNode(node) {
    return node.nodeType == 3;
}

function hasText(node, text) {
    return node.nodeValue.trim() == text;
}

var nodes = $("#root").contents().filter(function() { 
    return isTextNode(this) && hasText(this, '"Button Label"');
});

nodes.replaceWith("New Label");

Here's an example.

Upvotes: 0

Jishnu A P
Jishnu A P

Reputation: 14382

$("#div-id").html(function(i,oldhtml){
    return oldhtml.replace("Button Label","New label");
});

Upvotes: 1

Marko
Marko

Reputation: 72222

Here's one solution. Save the children of the div, set the text, and then append the chilrden back to it.

var $children = $myDiv.children();
$myDiv.text("New Button Label").append($children);

Example.

Upvotes: 2

Related Questions