简体   繁体   中英

How could I find an element with similar ID in JS?

In my page I have labels that look like this:

ContentPlaceHolder1_gvGroups_lblName_0

with corrosponding:

ContentPlaceHolder1_gvGroups_lblHidden_0

I can assert that any *lblName has a corrosponding *lblHidden.

Now, I have some js:

//use to make any label with 'edit' class editable
function makeLabelsEditable() {

    $(".edit").focusout(function () {
        setLabel(this);
    });

    $(".edit").click(function () {
        editLabel(this);
    });
}

//used to edit labels
function editLabel(source) {
    source.innerHTML = '<input type="text" maxlength="40" value="' + source.innerHTML + '"/>';
    $(source).unbind('click');
    source.children[0].focus()
}

//used to edit labels
function setLabel(source) {

    if (source.children[0].value != '') {
        $(source).click(function () {
            editLabel(this);
        });
        source.innerHTML = source.children[0].value;
    }

}

I can assert that anything marked with class edit will be valid.

I need to modify this code like so: //used to edit labels

function setLabel(source) {

    if (source.children[0].value != '') {
        $(source).click(function () {
            editLabel(this);
        });
        source.innerHTML = source.children[0].value;
        var hidden = someHowGetHiddenFromSource(source);
        hidden.innerHTML = source.children[0].value;
    }

}

I'm sure this is possible, I just do not know how.

Essentially, it would be something like:

getElementByID(replace(source.id,'lblName','lblHidden'));

I just do not know what JS / JQ functions can do that.

Thanks

Essentially, it would be something like: getElementByID(replace(source.id,'lblName','lblHidden'));

That's almost exactly it. It's:

var hidden = document.getElementById(source.id.replace('lblName', 'lblHidden'));

hidden will be the DOM element.

Or using jQuery:

var hidden = $("#" + source.id.replace('lblName', 'lblHidden'));

hidden will be a jQuery instance wrapping the element.

The id property of DOM elements is a string. JavaScript strings have a replace function which accepts, in the simple case, the string to replace and the replacement string. (There's more to it than that, but that's all you need in this case.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM