最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - How can I get an element's title property in JavaScript by element id? - Stack Overflow

programmeradmin4浏览0评论

I want to get an element by its id and get the title attribute. Say I had a div like below with a title attribute and an id. I want to get that title by providing the ID of the div.

<div id="myId" title="HeresMyTitle">Hello!</div>

I want to provide myId for the id and receive back "HeresMyTitle" without the quotes. Is there a way I can easily do this with out much more?

I want to get an element by its id and get the title attribute. Say I had a div like below with a title attribute and an id. I want to get that title by providing the ID of the div.

<div id="myId" title="HeresMyTitle">Hello!</div>

I want to provide myId for the id and receive back "HeresMyTitle" without the quotes. Is there a way I can easily do this with out much more?

Share Improve this question edited May 4, 2016 at 3:46 Seth 10.5k10 gold badges48 silver badges69 bronze badges asked May 4, 2016 at 2:56 TheGod39TheGod39 5532 gold badges5 silver badges7 bronze badges 1
  • $('#myId').attr('title') do this – guradio Commented May 4, 2016 at 2:57
Add a ment  | 

4 Answers 4

Reset to default 10

With jQuery:

var myTitle = $('#myId').attr('title');

without jQuery:

var myTitle = document.getElementById('myId').getAttribute('title');

Javascript:

var myTitle = document.getElementById('myId').title

Source: https://www.w3schools./jsref/prop_html_title.asp

As you have asked to do it in js, you can use getAttribute("title") to retrieve the title. Follow this snippet:

<div id="myId" title="HeresMyTitle">Hello!</div>

<script>
  
  var divId = document.getElementById("myId");
  
  alert(divId.getAttribute("title"));
  
 </script>

$('#myId').attr('title')

use .attr()

Get the value of an attribute for the first element in the set of matched elements.

alert($('#myId').attr('title'))
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myId" title="HeresMyTitle">Hello!</div>

发布评论

评论列表(0)

  1. 暂无评论