Jquery получить тег html

How to get tag name of an element in jQuery

There are various types of HTML elements such as input elements, anchor tags, drop downs etc. Each element has a unique syntax by which it is defined and identified. This syntax is its tag name. For Example, an input element is defined using tag, anchor element by tag, drop down by tag and so on. You can easily select an element in jQuery by its id or class using # (hash) or . (dot) operators. But how will you get the tag name of the selected element. Read on . Let’s define a sample HTML code which shall be used in the given examples :

Method 1 : Using tagName property of element directly
Select the element using any of the selector (either id or class) and use tagName property of the element to get the tag of that element. Referring the above HTML code, this is how we can get the tag names of both the elements given in it :

$("#textInput").tagName; $(".codippa").tagName;

If there are more than one elements matching the given selector such as when using the class selector most probably more than one element will be fetched. In those cases get the tag of the desired element using the index of element. This can be done using either of the following ways :

Читайте также:  Html тілінде гиперсілтеме бойынша ауысу

Method 2 : Using nodeName property of element

Select the element using any of the selector (either id or class) and use nodeName property of the element to get the tag of that element. Following code gets the tag names of the elements defined in the above HTML :

$("#textInput").nodeName; $(".codippa").nodeName;

Output will be :

If there are more than one elements matching the given selector such as when using the class selector most probably more than one element will be fetched. In those cases get the tag of the desired element using the index of element. This can be done using either of the following ways :

Method 3 : Using tagName property of element through prop method

Select the element whose tag is required using jQuery’s id or class selectors and the call prop method passing in tagName property as :

$("#textInput").prop("tagName"); $(".codippa").prop("tagName");

As before if there are more than one element matching the given selector then select it using index as :

Output will be :

Let’s tweak in :

  1. Method 3 should only be applied when the jQuery version being used is 1.6 or greater.
  2. All the above methods return tag names in upper case letters. Call toLowerCase() method on the returned value to get the tag names in lower case.

Add some more methods to the above list by commenting below. coDippa .

Share if it’s worth .

Источник

.html()

Мы можем использовать метод .html() для получения содержимого элемента. Если под селектор попадут несколько элементов, то будет извлечён только первый:

Данные будут извлечены из первого с искомым классом :

Данный метод использует нативное свойство innerHTML. Некоторые браузеры могут возвратить результат не совсем в таком виде, в котором он присутствует на странице. К примеру, Internet Explorer иногда упускает кавычки у значений атрибутов.

Пример:

Преобразуем html в текст, при клике по параграфу.

    p < margin:8px; font-size:20px; color:blue; cursor:pointer; >b < text-decoration:underline; >button    

Click to change the html

to a text node.

This does nothing.

Метод .html() может использоваться так же для замещения содержимого элемента.

Возьмём следующий HTML фрагмент:

Контент элемента может быть задан следующим образом:

$('div.demo-container') .html('

All new content. You bet!

');

Данная строчка заменит содержимое элемента :

Начиная с jQuery 1.4, метод .html() позволяет формировать HTML контент элемента в отдельной функции.

$('div.demo-container').html(function() < var emph = '' + $('p').length + ' paragraphs!'; return '

All new content for ' + emph + '

'; >);

Дан документ с шестью параграфами. Заменим их содержимое с на

All new content for 6 paragraphs!

.

Примеры

Пример: добавляем html каждому из div-ов

    .red   Hello    

Пример: добавляем html каждому из , а затем сразу же дополняем его содержимое.

    div       

Связанные уроки:

15 особенностей jQuery 1.4

jQuery постоянно развивается. Релиз версии 1.4 состоялся в январе. jQuery 1.4 получила много новых функций, расширений и имеет значительно лучшую производительность. Данная статья посвящена описанию основных улучшений jQuery 1.4.

Доступ к элементам контента с помощью jQuery

jQuery даёт возможность работать с элементами HTML и их содержимым различными способами. Например, вы можете добавить новые элементы внутрь, вокруг, до и после существующих элементов; вы можете заменить один элемент другим (или другими); вы можете читать и заменять содержимое элементов.

Шпаргалка jQuery:

  • Ajax
    • Global Ajax Event Handlers
      • .ajaxComplete()
        • :button
        • :checkbox
        • :checked
        • :disabled
        • :enabled
        • :file
        • :focus
        • :image
        • .serializeArray()
        • .serialize()
        • jQuery.param()
        • jQuery.ajax()
        • jQuery.ajaxSetup()
        • jQuery.ajaxPrefilter()
        • jQuery.ajaxTransport()
        • jQuery.get()
        • jQuery.post()
        • .load()
        • jQuery.getJSON()
        • jQuery.getScript()
        • .serialize()
        • .serializeArray()
        • jQuery.param()
        • .val()
        • .blur()
        • .change()
        • .focus()
        • .addClass()
        • .hasClass()
        • .removeClass()
        • .toggleClass()
        • .html()
        • .removeAttr()
        • .prop()
        • .removeProp()
        • .attr()
        • .val()
        • Collection Manipulation
          • jQuery.param()
          • .data()
          • .removeData()
          • Class Attribute
            • .addClass()
            • .hasClass()
            • .removeClass()
            • .toggleClass()
            • .clone()
            • .wrap()
            • .wrapAll()
            • .wrapInner()
            • .unwrap()
            • .append()
            • .appendTo()
            • .html()
            • .text()
            • .prepend()
            • .prependTo()
            • .after()
            • .before()
            • .insertAfter()
            • .insertBefore()
            • .unwrap()
            • .remove()
            • .empty()
            • .detach()
            • .replaceAll()
            • .replaceWith()
            • .removeProp()
            • .removeAttr()
            • .prop()
            • .attr()
            • .val()
            • .css()
            • .height()
            • .width()
            • .innerHeight()
            • .innerWidth()
            • .outerHeight()
            • .outerWidth()
            • .offset()
            • .position()
            • .scrollLeft()
            • .scrollTop()
            • .height()
            • .width()
            • .innerHeight()
            • .innerWidth()
            • .outerHeight()
            • .outerWidth()
            • jQuery.holdReady()
            • jQuery()
            • jQuery.noConflict()
            • jQuery.when()
            • .addClass()
            • .hasClass()
            • .removeClass()
            • .toggleClass()
            • .css()
            • .height()
            • .width()
            • .innerHeight()
            • .innerWidth()
            • .outerHeight()
            • .outerWidth()
            • .offset()
            • .position()
            • .scrollLeft()
            • .scrollTop()
            • .clearQueue()
            • .dequeue()
            • .data()
            • jQuery.hasData()
            • jQuery.removeData()
            • jQuery.dequeue()
            • .removeData()
            • jQuery.data()
            • .queue()
            • Custom
              • .clearQueue()
              • .dequeue()
              • .queue()
              • .clearQueue()
              • .dequeue()
              • jQuery.dequeue()
              • jQuery.data()
              • .queue()
              • jQuery.proxy()
              • callbacks.add()
              • callbacks.disable()
              • callbacks.disabled()
              • callbacks.empty()
              • callbacks.fire()
              • callbacks.fired()
              • callbacks.fireWith()
              • callbacks.has()
              • callbacks.lock()
              • callbacks.locked()
              • callbacks.remove()
              • jQuery.Callbacks()
              • deferred.always()
              • deferred.done()
              • deferred.fail()
              • deferred.notify()
              • deferred.notifyWith()
              • deferred.progress()
              • deferred.promise()
              • deferred.reject()
              • deferred.rejectWith()
              • deferred.resolve()
              • deferred.resolveWith()
              • deferred.state()
              • deferred.then()
              • Basics
                • Универсальный селектор (“*”)
                • jQuery( «.class» )
                • Селектор элементов (“element”)
                • Селектор ID (“#id”)
                • Множественный (“selector1, selector2, selectorN”)
                • Селектор по префиксу [name|=”value”]
                • Селектор содержащий значение [name*=»value»]
                • Селектор, содержащий слово [name~=»value»]
                • Селектор по атрибуту, на конце которого [name$=»value»]
                • Селектор по равенству [name=»value»]
                • Селектор по неравенству [name!=»value»]
                • Значение атрибута начинается с [name^=»value»]
                • Селектор по наличию атрибута [name]
                • Множественный селектор по атрибуту [name=»value»][name2=»value2″]
                • :animated Selector
                • :eq()
                • :even
                • :first
                • :focus
                • :gt()
                • :header
                • :lang()
                • :last
                • :lt()
                • :first-child
                • :first-of-type
                • :last-child
                • :last-of-type
                • :nth-child()
                • :nth-last-child()
                • :nth-last-of-type()
                • :nth-of-type()
                • :only-child
                • :only-of-type
                • :contains()
                • :empty
                • :has()
                • :parent
                • Browser Events
                  • .resize()
                  • .scroll()
                  • .ready()
                  • .bind()
                  • .delegate()
                  • jQuery.proxy()
                  • .off()
                  • .one()
                  • .trigger()
                  • .triggerHandler()
                  • .unbind()
                  • .undelegate()
                  • event.currentTarget
                  • event.data
                  • event.delegateTarget
                  • event.isDefaultPrevented()
                  • event.isImmediatePropagationStopped()
                  • event.isPropagationStopped()
                  • event.metaKey
                  • event.namespace
                  • event.pageX
                  • event.pageY
                  • event.preventDefault()
                  • event.relatedTarget
                  • event.result
                  • event.stopImmediatePropagation()
                  • event.stopPropagation()
                  • event.target
                  • event.timeStamp
                  • event.type
                  • event.which
                  • .blur()
                  • .change()
                  • .focus()
                  • .focusin()

                  Источник

                  jQuery. Как получить содержимое тэга или элемента на странице.

                  Бывают ситуации, что нужно получить внутреннее содержимое элемента (тэга) на странице.

                  Нужно во всплывающем окне вывести информацию, которая написана внутри элемента div с >

                  1 вариант. Вам нужно получить html-код, который находится внутри элемента.

                  В этом случае нужно воспользоваться методом html().

                  В исходный пример нужно внести совсем небольшие изменения:

                  Окно с таким содержимым мы получим в результате.

                  13-05-2013 15-00-30

                  Обратите внимание, что все тэги, которые были внутри элемента, тоже будут выведены.

                  2 вариант. Вам нужно получить только текстовое содержимое.

                  Для этого нужно внести очень небольшое изменение в скрипт: вместо метода html() воспользоваться методом text().

                  Вот, как это будет выглядеть:

                  В результате, в окне будет выведен только текст и все теги будут проигнорированы:

                  13-05-2013 11-00-55

                  Хочу сказать, что на практике пользоваться такими методами приходится очень часто, поэтому имейте их в виду и применяйте по месту.

                  Все мои уроки по Javascript здесь.

                  Чтобы оставить сообщение, зарегистрируйтесь/войдите на сайт через:

                  Источник

                  jQuery. Как получить содержимое тэга или элемента на странице.

                  Бывают ситуации, что нужно получить внутреннее содержимое элемента (тэга) на странице.

                  Нужно во всплывающем окне вывести информацию, которая написана внутри элемента div с >

                  1 вариант. Вам нужно получить html-код, который находится внутри элемента.

                  В этом случае нужно воспользоваться методом html().

                  В исходный пример нужно внести совсем небольшие изменения:

                  Окно с таким содержимым мы получим в результате.

                  13-05-2013 15-00-30

                  Обратите внимание, что все тэги, которые были внутри элемента, тоже будут выведены.

                  2 вариант. Вам нужно получить только текстовое содержимое.

                  Для этого нужно внести очень небольшое изменение в скрипт: вместо метода html() воспользоваться методом text().

                  Вот, как это будет выглядеть:

                  В результате, в окне будет выведен только текст и все теги будут проигнорированы:

                  13-05-2013 11-00-55

                  Хочу сказать, что на практике пользоваться такими методами приходится очень часто, поэтому имейте их в виду и применяйте по месту.

                  Все мои уроки по Javascript здесь.

                  Чтобы оставить сообщение, зарегистрируйтесь/войдите на сайт через:

                  Источник

Оцените статью