Comment element ID attribute

Asked

Viewed 175 times

0

I have a question in Jquery and I would like to know if this is possible.

I have an element:

<input type="text" id="meuid" class="minhaclasse" >

I would like my property id to be dead, but can activate it, for example by commenting and removing the comment:

<input type="text" /*id="meuid"*/ class="minhaclasse" >

Is that possible? Any suggestions for doing this?

  • I know there is a way to remove $("p"). removeAttr("id");

  • Yes, there really is. But I need you to just comment, because if you remove there is no way to return it.

  • What if it renames? Does it? for example: id="meuid" for old-id="meuid"

  • Interesting, how does it work ? @Fabianocacinpinel

  • you would have to save the id value, remove the id and add the old-id attribute with the saved value, so I searched there is nothing ready to rename an attribute, but maybe you could solve by renaming the id, so id="@meuid" That would make it easy as $('#meuid'). attr('id','@meuid'); . Perhaps it would be easier for you to explain better what you do than to do. You should have another solution without having to do this.

  • if you explain the reason for doing so, you may have a more appropriate solution.

Show 1 more comment

4 answers

1

Possible is not in all browsers as they remove comments from tags. Commenting on the attribute is dangerous as it is necessary to modify the outerHTML of its element, which ends up recreating/removing its elements (if they have a Javascript reference, they will only be killed, but can be declared on the page again with HTMLElement().appendChild, etc..).

To better understand, test this snippet:

// Observação: em navegadores modernos, elementos com id
// são disponíveis em 'window' se tiverem caracteres válidos.

var minhaDiv = div;

document.body.innerHTML = '<div id="div">hey</div>';

// "old"
alert("Velha div: " + minhaDiv.innerHTML);

// "hey" - essa não é mais a 'minhaDiv'
alert("Nova div: " + div.innerHTML);
<div id="div">old</div>

Note: To comment on HTML is used <!---->.

Modifying an element’s "id" will only make a complication with its code.

Continuing, it would be better if you add/remove the attribute "id" with the value always memorized, for example:

// Você pode usar diretamente 'removeAttr' e
// 'attr' (com o id específico) para remover/adicionar o atributo id
// (portanto, é necessário
// jQuery.fn.each para percorrer cada elemento em uma função
// de toggle)

jQuery.fn.toggleAttr = function(attrName, value) {

    this.each(function() {

        // this é um elemento puro do JavaScript aqui, então:
        // $(this) --> lista de elementos do jQuery
        var $me = $(this);

        // verifica se o atributo não existe (ou se é inativo)
        if ($me.attr(attrName) === undefined || $me.attr(attrName) === false) {
            $me.attr(attrName, value);

        } else $me.removeAttr(attrName);
    });
};

var $input = $("#meuid");

// memoriza o id
var id = $input.attr('id');

// remove o atributo id
$input.toggleAttr("id", id);

// adiciona o atributo id
$input.toggleAttr("id", id);

1

Possible to comment, but html not familiar <input /*id="blabla"*/> and only exchange element id for _id. Sending the code below, very simple code to two form jquery or pure javascript to better understand.

/* jQuery */
var elemento1 = $('[id="meuid1"]');
var nome1 = elemento1.attr('id');
elemento1.removeAttr('id').attr('_id', nome1);

/* Javascript Puro */
var elemento2 = document.querySelector('[id="meuid2"]');
var nome2 = elemento2.getAttribute('id');
elemento2.removeAttribute('id');
elemento2.setAttribute('_id', nome2);

/* Resultado de Console */
console.log($('.minhaclasse')[0]);
console.log($('.minhaclasse')[1]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
jQuery<br>
<input type="text" id="meuid1" class="minhaclasse">
<br><br>
Javascript Puro<br>
<input type="text" id="meuid2" class="minhaclasse">

1

Follow an implementation with some controls to ensure the integrity of properties.

var AttrManager = function (element) {
  this.attr = {};
  this.element = element;
}

AttrManager.prototype.toggle = function (name) {
  if (name in this.attr) {
    this.element.setAttribute(name, this.attr[name]);
    delete this.attr[name];
  } else {
    this.attr[name] = this.element.getAttribute(name);
    this.element.removeAttribute(name);
  }
}

var teste = document.getElementById("teste");
var attrManager = new AttrManager(teste);

console.log(teste);
attrManager.toggle("id");
console.log(teste);
attrManager.toggle("data-teste");
console.log(teste);
attrManager.toggle("data-teste");
console.log(teste);
attrManager.toggle("id");
console.log(teste);
<div id="teste" class="teste" data-teste>
</div>

  • It seems that the op is asking how to do this with the use of jQuery but good solution

0

What I would do in that case is this:

<input type="text" data-id="minhaId">

data-id would be a generic field with my id just to store it through html and when I needed to activate my id would:

//PEGO O VALOR DA ID FAKE

   valor_na_fake_id = $("data-id").val();

//COLOCO DE VOLTA NO ELEMENTO COMO ID

    $("data-id").attr('id',valor_na_fake_id);

// O RESULTADO SERIA

    <input type="text" data-id="minhaId" id="minhaId">

Browser other questions tagged

You are not signed in. Login or sign up in order to post.