development

jQuery가 태그 이름을 제공 할 수 있습니까?

big-blog 2020. 7. 21. 07:32
반응형

jQuery가 태그 이름을 제공 할 수 있습니까?


HTML 페이지에 동일한 클래스를 가진 여러 요소가 있지만 요소 유형이 다릅니다. 반복 할 때 요소의 태그 이름을 찾고 싶습니다. .attr은 "tag"또는 "tagname"을 사용하지 않습니다.

여기 내가 의미하는 바가 있습니다. 페이지에서 다음 요소를 고려하십시오.

<h1 class="rnd">First</h1>
<h2 id="foo" class="rnd">Second</h2>
<h3 class="rnd">Third</h3>
<h4 id="bar" class="rnd">Fourth</h4>

이제 다음과 같이 실행하여 내 요소가 아직 정의되지 않은 경우 모든 요소에 ID가 있는지 확인하려고합니다.

$(function() {
  $(".rnd").each(function(i) {
    var id = $(this).attr("id");
    if (id === undefined || id.length === 0) {
      // this is the line that's giving me problems.
      // .attr("tag") returns undefined
      $(this).attr("id", "rnd" + $(this).attr("tag") + "_" + i.toString());
    }
  });
});

결과는 H2 및 H4 요소의 ID가

rndh2_1
rndh4_3

각기.

"this"로 표시되는 요소의 태그 이름을 발견하는 방법에 대한 아이디어가 있습니까?


$(this).attr("id", "rnd" + $(this).attr("tag") + "_" + i.toString());

해야한다

$(this).attr("id", "rnd" + this.nodeName.toLowerCase() + "_" + i.toString());

당신은 이것을 시도 할 수 있습니다 :

if($(this).is('h1')){
  doStuff();
}

is ()에 대한 자세한 내용은 문서참조하십시오 .


이전 에이 질문을 한 번 this겪었으므로 내 경우에는 도움이되지 않았습니다 (.가 없지만 jQuery 선택기 인스턴스가 있음). 호출 get()하면 HTML 요소 nodeName가 생겨 위에서 언급 한대로 HTML 요소를 얻을 수 있습니다 .

this.nodeName; // In a event handler, 'this' is usually the element the event is called on

또는

$('.hello:first-child').get(0).nodeName; // Use 'get' or simply access the jQuery Object like an array
$('.hello:first-child')[0].nodeName;     // will get you the original DOM element object

$(this).prop('tagName');jQuery 1.6 이상을 사용 하는 경우 에도 사용할 수 있습니다 .


예. 아래 코드를 사용할 수 있습니다.

this.tagName

nodeNamenodeName은 DOM 속성이고 jQuery 자체에는 nodeName함수 또는 속성 이 없으므로 jQuery에서 사용할 수 없다고 생각합니다 . 그러나이 nodeName물건 에 대해 처음 언급 한 응답자를 기반으로 다음과 같이 문제를 해결할 수있었습니다.

this.attr("id", "rnd" + this.attr("nodeName") + "_" + i.toString());

참고 : this여기 jQuery 객체가 있습니다.


이것은 jquery tagname 첫 번째 자식 을 쿼리로 사용하여 Google에 나오는 질문이므로 다른 예를 게시합니다.

<div><p>Some text, whatever</p></div>

$('div').children(':first-child').get(0).tagName); // ...and not $('div:first-child')[...]

jquery 결과는 (대문자) 태그 이름입니다. P


전체 페이지에서 html 요소 태그 이름을 얻을 수 있습니다.

당신은 사용할 수 있습니다 :

        $('body').contents().on("click",function () {
          var string = this.tagName;
          alert(string);
         });

you can try:
jQuery(this).get(0).tagName;
or
jQuery(this).get(0).nodeName;

참고 : 이것을 선택기로 교체하십시오 (h1, h3 또는 ...)


나는 단지 다른 문제를 위해 그것을 썼고 그것이 당신에게도 도움이 될 것이라고 생각했습니다.

용법:

  • onclick="_DOM_Trackr(this);"

매개 변수 :

  1. 추적 할 DOM 객체
  2. 리턴 / 경고 스위치 (선택 사항, 기본값 = 경고)

소스 코드:

function _DOM_Trackr(_elem,retn=false)
{
    var pathTrackr='';
    var $self=$(_elem).get(0);
    while($self && $self.tagName)
    {
        var $id=($($self).attr("id"))?('#'+$($self).attr("id")):'';
        var $nName=$self.tagName;
        pathTrackr=($nName.toLowerCase())+$id+((pathTrackr=='')?'':' > '+(pathTrackr));
        $self=$($self).parent().get(0);
    }
    if (retn)
    {
        return pathTrackr;
    }
    else
    {
        alert(pathTrackr);
    }
}

문제를 해결하는 가장 좋은 방법 $(this).attr("tag")this.nodeName.toLowerCase()또는 로 바꾸는 것 입니다 this.tagName.toLowerCase().

둘 다 똑같은 결과를 낳습니다!


빠른 FILTER 방법을 고려하십시오 .

$('.rnd').filter('h2,h4')

보고:

[<h2 id=​"foo" class=​"rnd">​Second​</h2>​, <h4 id=​"bar" class=​"rnd">​Fourth​</h4>​]

그래서:

$('.rnd').filter('h2,h4').each(function() { /*...$(this)...*/ });

대신 간단하게 수행하십시오.

$(function() {
  $(".rnd").each(function(i) {
    var id = $(this).attr("id");
    if (id === undefined || id.length === 0) {
      // this is the line that's giving me problems.
      // .attr("tag") returns undefined
      // change the below line...
      $(this).attr("id", "rnd" + this.tagName.toLowerCase() + "_" + i.toString()); 
  });
});

참고URL : https://stackoverflow.com/questions/1532331/can-jquery-provide-the-tag-name

반응형